package ml.kupin.sso.controller;

import com.alibaba.fastjson.JSON;
import ml.kupin.common.utils.CookieUtils;
import ml.kupin.common.utils.KuPinResult;
import ml.kupin.sso.service.TokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录信息检查Controller
 * <p>
 * Created by 小柯(Allen Kerr) on 17.5.6 16:37.
 */
@Controller
@RequestMapping("/user")
public class TokenController {

    @Autowired
    private TokenService tokenService;

    @Value("${token_cookie_name}")
    private String token_cookie_name;

    /**
     * 接受页面发送的Ajax请求，检查用户是否登录
     * url : http://localhost:8088/user/token/{token}
     * 返回值： json数据 ——> 使用 KupinResult 包装 Tbuser 对象。
     */
    //MediaType.APPLICATION_JSON_UTF8_VALUE = "application/json" + ";charset=UTF-8";
    /*@RequestMapping(value = "/token/{token}", method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String checkToken(@PathVariable String token, String callback) {
        //调用服务层查询redis中是否有与token对应的数据
        KuPinResult kuPinResult = tokenService.getUserByTokenFromRedis(token);
        String jsonString = JSON.toJSONString(kuPinResult);
//        System.out.println(jsonString);

        //响应结果前，先判断请求是否为 jsonp 请求
        if (StringUtils.isNotBlank(callback)) {
            //jsonp请求，需要对结果进行处理
            return callback + "(" + jsonString + ");";
        }
        return jsonString;
    }*/
    @RequestMapping(value = "/token/{token}", method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Object checkToken(@PathVariable String token, String callback) {
        //调用服务层查询redis中是否有与token对应的数据
        KuPinResult kuPinResult = tokenService.getUserByTokenFromRedis(token);
        //响应结果前，先判断请求是否为 jsonp 请求
        if (StringUtils.isNotBlank(callback)) {
            //jsonp请求，需要对结果进行处理
            //Spring4.1以后，无需手动拼接字符串
            MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(kuPinResult);
            mappingJacksonValue.setJsonpFunction(callback);
            return mappingJacksonValue;
        }
        //非jsonp请求
        return kuPinResult;
    }

    /**
     * 用户注销登录，需要清除cookie中的token和redis中的token
     * http://localhost:8088/user/logout/{token}
     */
    @RequestMapping("/logout/{token}")
    public String logout(@PathVariable String token, HttpServletRequest request, HttpServletResponse response) {
        //调用服务层删除redis中与token对应的key
        boolean result = tokenService.removeTokenFromRedis(token);//result：是否删除成功，好像也没啥用
        //删除cookie中的token
        CookieUtils.deleteCookie(request, response, token_cookie_name);
        return "redirect:/user/login";
    }

}
